package com.train.user.controller;

import com.train.common.annotation.Anonymous;
import com.train.common.core.controller.BaseController;
import com.train.common.core.domain.AjaxResult;
import com.train.common.core.page.PageDomain;
import com.train.common.core.page.TableDataInfo;
import com.train.common.core.page.TableSupport;
import com.train.common.constant.HttpStatus;
import com.train.user.domain.UserPlan;
import com.train.user.service.UserPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 用户计划 控制器
 *
 * @author train
 */
@RestController
@RequestMapping("/user/plan")
public class UserPlanController extends BaseController {

    @Autowired
    private UserPlanService userPlanService;

    /**
     * 获取当前登录用户ID
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        // 使用BaseController提供的方法获取当前登录用户ID
        return getUserId();
    }

    /**
     * 创建计划
     * @param request 创建计划请求
     * @return 结果
     */
    @PostMapping
    public AjaxResult createPlan(@RequestBody Map<String, Object> request) {
        try {
            // 参数校验
            String planName = (String) request.get("planName");
            String planType = (String) request.get("planType");
            
            if (planName == null || planName.isEmpty()) {
                return AjaxResult.error(400, "计划名称不能为空");
            }
            if (planType == null || (!"1".equals(planType) && !"2".equals(planType))) {
                return AjaxResult.error(400, "计划类型错误");
            }

            // 直接使用BaseController的getUserId()方法获取当前登录用户ID
            Long userId = getUserId();
            UserPlan userPlan = userPlanService.createPlan(userId, planName, planType);
            
            // 构建响应数据
            Map<String, Object> data = new java.util.HashMap<>();
            data.put("planId", userPlan.getPlanId());
            data.put("planName", userPlan.getPlanName());
            data.put("planType", userPlan.getPlanType());
            data.put("totalDuration", userPlan.getTotalDuration());
            data.put("completedDuration", userPlan.getCompletedDuration());
            data.put("status", userPlan.getStatus());
            data.put("createTime", userPlan.getCreateTime());
            
            return AjaxResult.success("创建成功", data);
        } catch (RuntimeException e) {
            if (e.getMessage().equals("该计划名称已存在")) {
                return AjaxResult.error(400, e.getMessage());
            }
            // 添加更详细的错误日志
            logger.error("创建计划失败: {}", e.getMessage(), e);
            return AjaxResult.error(500, "创建失败: " + e.getMessage());
        }
    }

    /**
     * 修改计划
     * @param planId 计划ID
     * @param request 更新计划请求
     * @return 结果
     */
    @PutMapping("/{planId}")
    @Anonymous
    public AjaxResult updatePlan(@PathVariable Long planId, @RequestBody Map<String, Object> request) {
        try {
            if (planId == null) {
                return AjaxResult.error(400, "计划ID不能为空");
            }

            // 获取请求参数
            String planName = (String) request.get("planName");
            String status = (String) request.get("status");

            // 验证状态值
            if (status != null && !"0".equals(status) 
                    && !"1".equals(status) && !"2".equals(status)) {
                return AjaxResult.error(400, "状态值错误");
            }

            Long userId = getCurrentUserId();
            UserPlan userPlan = userPlanService.updatePlan(userId, planId, planName, status);
            
            // 构建响应数据
            Map<String, Object> data = new java.util.HashMap<>();
            data.put("planId", userPlan.getPlanId());
            data.put("planName", userPlan.getPlanName());
            data.put("planType", userPlan.getPlanType());
            data.put("totalDuration", userPlan.getTotalDuration());
            data.put("completedDuration", userPlan.getCompletedDuration());
            data.put("status", userPlan.getStatus());
            data.put("updateTime", userPlan.getUpdateTime());
            
            return AjaxResult.success("更新成功", data);
        } catch (RuntimeException e) {
            if (e.getMessage().equals("计划不存在或无权限")) {
                return AjaxResult.error(403, "无权限修改该计划");
            } else if (e.getMessage().contains("不存在")) {
                return AjaxResult.error(404, "计划不存在");
            } else if (e.getMessage().equals("该计划名称已存在")) {
                return AjaxResult.error(400, e.getMessage());
            }
            return AjaxResult.error(500, "更新失败");
        }
    }

    /**
     * 删除计划
     * @param planId 计划ID
     * @param confirm 是否确认删除
     * @return 结果
     */
    @DeleteMapping("/{planId}")
    @Anonymous
    public AjaxResult deletePlan(@PathVariable Long planId, @RequestParam Boolean confirm) {
        try {
            if (planId == null) {
                return AjaxResult.error(400, "计划ID不能为空");
            }
            if (confirm == null || !confirm) {
                return AjaxResult.error(400, "请确认删除操作");
            }

            Long userId = getCurrentUserId();
            userPlanService.deletePlan(userId, planId);
            
            return AjaxResult.success("删除成功");
        } catch (RuntimeException e) {
            if (e.getMessage().equals("计划不存在或无权限")) {
                return AjaxResult.error(403, "无权限删除该计划");
            } else if (e.getMessage().contains("不存在")) {
                return AjaxResult.error(404, "计划不存在");
            }
            return AjaxResult.error(500, "删除失败");
        }
    }

    /**
     * 查看计划列表
     * @param planType 计划类型
     * @param status 状态
     * @return 分页结果
     */
    @GetMapping("/list")
    @Anonymous
    public TableDataInfo getUserPlans(@RequestParam(required = false) String planType, 
                                     @RequestParam(required = false) String status) {
        try {
            Long userId = getCurrentUserId();
            startPage(); // 开启分页
            
            // 调用服务层方法获取数据，直接传递pageNum和pageSize
            PageDomain pageDomain = TableSupport.buildPageRequest();
            List<UserPlan> plans = (List<UserPlan>) userPlanService.getUserPlans(userId, pageDomain.getPageNum(),
                                                             pageDomain.getPageSize(), planType, status);
            
            // 使用getDataTable处理List数据
            return getDataTable(plans);
        } catch (Exception e) {
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(HttpStatus.ERROR);
            dataInfo.setMsg("查询失败");
            return dataInfo;
        }
    }

    /**
     * 查看计划详情
     * @param planId 计划ID
     * @return 结果
     */
    @GetMapping("/{planId}")
    @Anonymous
    public AjaxResult getPlanDetail(@PathVariable Long planId) {
        try {
            if (planId == null) {
                return AjaxResult.error(400, "计划ID不能为空");
            }

            Long userId = getCurrentUserId();
            Map<String, Object> detail = userPlanService.getPlanDetail(userId, planId);
            
            return AjaxResult.success("查询成功", detail);
        } catch (RuntimeException e) {
            if (e.getMessage().equals("计划不存在或无权限")) {
                return AjaxResult.error(404, "计划不存在");
            }
            return AjaxResult.error(500, "查询失败");
        }
    }
}